﻿#include "requirement_management_widget.h"
#include "ui_requirement_management_widget.h"
#include "requirement_edit_dialog.h"
#include <QUuid>
#include <QAbstractItemView>
#include <QDateTime>
#include "easylogging++.h"
#include "requirement_info_table.h"
#include <QDebug>
#include <QDropEvent>


RequirementManagementWidget::RequirementManagementWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RequirementManagementWidget),
    m_treeWidgetMenu(nullptr),
    m_currentMenuAtItem(nullptr)
{
    ui->setupUi(this);
    initUi();
    initMenu();
    initEvents();
}

RequirementManagementWidget::~RequirementManagementWidget()
{
    delete ui;
}

void RequirementManagementWidget::setPrjUuid(QString uuid)
{
    m_prjUuid = uuid;
    initRequirementData();
}

void RequirementManagementWidget::initUi()
{
    setAttribute(Qt::WA_StyledBackground);
    ui->treeWidget->setDragDropMode(QAbstractItemView::InternalMove);
    ui->treeWidget->setDragEnabled(true);
    ui->treeWidget->setAcceptDrops(true);
    ui->treeWidget->setDropIndicatorShown(true);
    ui->treeWidget->header()->setSectionResizeMode(QHeaderView::Stretch);
}

void RequirementManagementWidget::initEvents()
{
    connect(ui->newRequirementBtn, &QPushButton::clicked,
            this, &RequirementManagementWidget::onNewRequirementBtnClicked);
    connect(ui->treeWidget, &QTreeWidget::itemPressed, this,
            [=](QTreeWidgetItem* item, int column) {
        Q_UNUSED(column)
        m_currentMenuAtItem = item;
        if (qApp->mouseButtons() != Qt::RightButton)
        {
            ui->requirementDetailWidget->setRequirementUuid(item->data(0, Qt::UserRole).toString());
            return ;
        }

        m_treeWidgetMenu->exec(QCursor::pos());
    });

    connect(ui->treeWidget, &TreeWidget::itemIsMoved, this, [=](QTreeWidgetItem *item){
        QTreeWidgetItem *parent = item->parent();
        QString str = item->text(0);
        QString parentUuid = "";
        str += " is moved to ";
        if (nullptr == parent) {
            str += "top level.";
        } else {
            str += item->parent()->text(0);
            parentUuid = item->parent()->data(0, Qt::UserRole).toString();
        }
        LOG(DEBUG) << str.toStdString();
        RequirementInfoTable rit;
        rit.updateRequirementParentUuid(item->data(0, Qt::UserRole).toString(),
                                        parentUuid);
    });
}

void RequirementManagementWidget::initMenu()
{
    if (!m_treeWidgetMenu)
    {
        m_treeWidgetMenu = new QMenu(this);
        QAction *newChildTaskAction = new QAction(QStringLiteral("新建子需求"));
        QAction *editTaskAction = new QAction(QStringLiteral("编辑需求"));
        QAction *deleteTaskAction = new QAction(QStringLiteral("删除需求"));
        QAction *deleteChildTaskAction = new QAction(QStringLiteral("删除子需求"));

        m_treeWidgetMenu->addAction(newChildTaskAction);
        m_treeWidgetMenu->addAction(editTaskAction);
        m_treeWidgetMenu->addAction(deleteTaskAction);
        m_treeWidgetMenu->addAction(deleteChildTaskAction);

        connect(newChildTaskAction, &QAction::triggered,
                this, &RequirementManagementWidget::onNewChildRequirementActionTriggered);
        connect(editTaskAction, &QAction::triggered,
                this, &RequirementManagementWidget::onEditRequirementActionTriggered);
        connect(deleteTaskAction, &QAction::triggered,
                this, &RequirementManagementWidget::onDeleteRequirementActionTriggered);
        connect(deleteChildTaskAction, &QAction::triggered,
                this, &RequirementManagementWidget::onDeleteChildRequirementActionTriggered);
    }
}

void RequirementManagementWidget::initRequirementData()
{
    ui->treeWidget->clear();
    QList<QVariantList> data;
    RequirementInfoTable rit;
    bool ret = rit.selectAllByPrj(m_prjUuid, data);
    if (!ret)
    {
        LOG(ERROR) << "init prj task data failed";
        return ;
    }

    QString firstTaskUuid = "";

    QHash<QString, QTreeWidgetItem*> itemMap;
    for (int i = 0; i < data.count(); i++)
    {
        QString parentTaskUuid = data[i][1].toString();
        QString uuid = data[i][0].toString();
        QTreeWidgetItem* newItem = nullptr;
        if (itemMap.find(uuid) != itemMap.end())
        {
            newItem = itemMap[uuid];
            newItem->setText(0, data[i][2].toString());
            newItem->setText(1, data[i][3].toString());
        }
        else
        {
            newItem = new QTreeWidgetItem({data[i][2].toString(),
                                           data[i][3].toString()});
            newItem->setData(0, Qt::UserRole, uuid);
            newItem->setFlags(newItem->flags() | Qt::ItemIsDragEnabled);
        }

        itemMap[uuid] = newItem;

        if (0 == parentTaskUuid.size())
        {
            if (firstTaskUuid.isEmpty())
            {
                firstTaskUuid = newItem->data(0, Qt::UserRole).toString();
            }
            ui->treeWidget->addTopLevelItem(newItem);
        }
        else if (itemMap.find(parentTaskUuid) != itemMap.end())
        {
            QTreeWidgetItem* parentItem = itemMap[parentTaskUuid];
            parentItem->addChild(newItem);
        }
        else
        {
            QTreeWidgetItem* parentItem = new QTreeWidgetItem();
            parentItem->setData(0, Qt::UserRole, parentTaskUuid);
            parentItem->addChild(newItem);
            parentItem->setFlags(parentItem->flags() | Qt::ItemIsDragEnabled);
            itemMap[parentTaskUuid] = parentItem;
        }
    }

    LOG(DEBUG) << "set uuid: " << firstTaskUuid.toStdString();
    ui->requirementDetailWidget->setRequirementUuid(firstTaskUuid);
}


void RequirementManagementWidget::deleteTreeWidgetItem(QTreeWidgetItem *item)
{
    RequirementInfoTable rit;
    bool ret = rit.deleteRequirement(item->data(0, Qt::UserRole).toString());
    if (!ret)
    {
        return ;
    }

    for (int i = item->childCount() - 1; i >= 0; i--)
    {
        QTreeWidgetItem* childItem = item->child(i);
        deleteTreeWidgetItem(childItem);
        item->removeChild(childItem);
    }
}

void RequirementManagementWidget::onNewRequirementBtnClicked()
{
    RequirementEditDialog editDialog(this);
    if (editDialog.exec())
    {
        QString uuid                   = QUuid::createUuid().toString(QUuid::WithoutBraces);
        QString requirementName        = editDialog.getRequirementName();
        QString requirementDescription = editDialog.getRequirementDescription();
        QString currentTime            = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        RequirementInfoTable rit;
        bool ret = rit.insertNewRequirement(uuid,
                                        m_prjUuid,
                                        "",
                                        requirementName,
                                        requirementDescription,
                                        currentTime,
                                        currentTime,
                                        0);

        if (!ret)
        {
            return ;
        }

        QTreeWidgetItem* newItem = new QTreeWidgetItem({requirementName, requirementDescription});
        newItem->setData(0, Qt::UserRole, uuid);
        ui->treeWidget->addTopLevelItem(newItem);
    }
}

void RequirementManagementWidget::onNewChildRequirementActionTriggered()
{
    RequirementEditDialog editDialog(this);
    if (editDialog.exec())
    {
        QString uuid = QUuid::createUuid().toString(QUuid::WithoutBraces);
        QString requirementName = editDialog.getRequirementName();
        QString requirementDescription = editDialog.getRequirementDescription();
        QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        RequirementInfoTable rit;
        bool ret = rit.insertNewRequirement(uuid,
                                 m_prjUuid,
                                 m_currentMenuAtItem->data(0, Qt::UserRole).toString(),
                                 requirementName,
                                 requirementDescription,
                                 currentTime,
                                 currentTime,
                                 0);

        if (!ret)
        {
            return ;
        }

        QTreeWidgetItem* newItem = new QTreeWidgetItem({requirementName, requirementDescription});
        newItem->setData(0, Qt::UserRole, uuid);
        m_currentMenuAtItem->addChild(newItem);
    }
}

void RequirementManagementWidget::onEditRequirementActionTriggered()
{
    RequirementEditDialog editDialog(this);
    editDialog.setRequirementName(m_currentMenuAtItem->text(0));
    editDialog.setRequirementDescription(m_currentMenuAtItem->text(1));
    if (editDialog.exec())
    {
        QString uuid = m_currentMenuAtItem->data(0, Qt::UserRole).toString();
        QString parentUuid;
        QTreeWidgetItem* parentItem = m_currentMenuAtItem->parent();
        if (parentItem)
        {
            parentUuid = parentItem->data(0, Qt::UserRole).toString();
        }
        QString taskName = editDialog.getRequirementName();
        QString taskDescription = editDialog.getRequirementDescription();
        QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        RequirementInfoTable rit;
        bool ret = rit.updateRequirement(uuid,
                              parentUuid,
                              taskName,
                              taskDescription,
                              currentTime,
                              0);

        if (!ret)
        {
            return ;
        }

        m_currentMenuAtItem->setText(0, taskName);
        m_currentMenuAtItem->setText(1, taskDescription);
    }
}

void RequirementManagementWidget::onDeleteRequirementActionTriggered()
{
    RequirementInfoTable rit;
    bool ret = rit.deleteRequirement(m_currentMenuAtItem->data(0, Qt::UserRole).toString());
    if (!ret)
    {
        return ;
    }

    QTreeWidgetItem* parentItem = m_currentMenuAtItem->parent();
    if (parentItem)
    {
        parentItem->removeChild(m_currentMenuAtItem);
    }
    else
    {
        int index = -1;
        for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
        {
            if (ui->treeWidget->topLevelItem(i) == m_currentMenuAtItem)
            {
                index = i;
                break;
            }
        }

        if (index != -1)
        {
            delete ui->treeWidget->takeTopLevelItem(index);
        }
    }
}

void RequirementManagementWidget::onDeleteChildRequirementActionTriggered()
{
    RequirementInfoTable rit;
    bool ret = rit.deleteChildRequirement(m_currentMenuAtItem->data(0, Qt::UserRole).toString());
    if (!ret)
    {
        return ;
    }

    for(int i = m_currentMenuAtItem->childCount() - 1; i >= 0; i--)
    {
        QTreeWidgetItem *childItem = m_currentMenuAtItem->child(i);//删除子节点
        deleteTreeWidgetItem(childItem);
        m_currentMenuAtItem->removeChild(childItem);
    }
}
